import { AMAP_KEY, TIANDITU_KEY } from '@/environment';
import { convertLngLonToNumber, GCJ02ToWGS84 } from '@/utils/coordTransform';
import axios from 'axios';

interface POI {
  name: string;
  address: string;
  lonlat: string; // fot tianditu, "lng,lat", WGS84
  location: string; // for amap, "lng,lat", GCJ02
}

export interface PositionOption {
  label: string; // "name(address)"
  value: string; // "lng,lat", WGS84
  name: string; // "name"
}

enum TIANDITU {
  URL = 'https://api.tianditu.gov.cn/v2/search',
  type = 'query',
}

export function searchPositionsTianditu(
  keyWord: string,
  cityCode: string,
): Promise<PositionOption[]> {
  const postStr = {
    keyWord,
    specify: '156' + cityCode,
    queryType: 12,
    start: 0,
    count: 10,
    show: 1,
    dataTypes: '230101,230106,230107,230200',
  };

  const getPOI = (item: { resultType: number; pois?: POI[] }): PositionOption[] => {
    return (
      item.pois?.map((poi: POI) => ({
        label: `${poi.name}(${poi.address})`,
        value: poi.lonlat,
        name: poi.name,
      })) ?? []
    );
  };

  return axios
    .get(TIANDITU.URL, {
      params: { postStr: JSON.stringify(postStr), tk: TIANDITU_KEY, type: TIANDITU.type },
    })
    .then((res) => {
      if (res.status !== 200) return [];

      const options: PositionOption[] = [];
      for (const key in res.data) {
        const item = res.data[key];
        if (item.pois) {
          options.push(...getPOI(item));
        }
      }

      return options;
    });
}

enum AMAP {
  URL = 'https://restapi.amap.com/v3/place/text',
  types = '150000',
  extensions = 'base',
}

export function searchPositionsAmap(keyWord: string, cityCode: string): Promise<PositionOption[]> {
  return axios
    .get(AMAP.URL, {
      params: {
        key: AMAP_KEY,
        keywords: keyWord,
        city: cityCode,
        types: AMAP.types,
        extensions: AMAP.extensions,
      },
    })
    .then((res) => {
      if (res.status === 200 && res.data.status === '1') {
        return (
          res.data.pois?.map(
            (poi: POI): PositionOption => ({
              label: `${poi.name}(${poi.address})`,
              value: GCJ02ToWGS84(
                convertLngLonToNumber(poi.location)[0],
                convertLngLonToNumber(poi.location)[1],
              ).toString(),
              name: poi.name,
            }),
          ) ?? []
        );
      }

      return [];
    });
}
